package com.jrelax.third.fs.rmi;

import com.jrelax.third.fs.IRemoteFS;
import com.jrelax.third.fs.Run;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMISocketFactory;
import java.util.Properties;

/**
 * RMI启动服务
 * Created by zengchao on 2016-12-26.
 */
public class RMIService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static RMIService instance = null;
    private String host;
    private int port;

    public static RMIService getInstance(){
        if (instance == null) {
            instance = new RMIService();
        }
        return instance;
    }

    private RMIService() {
    }

    public void start(){
        logger.info("FS:RMI服务启动中....");
        try {
            String path = Run.class.getResource("/").getPath()+"/config.properties";
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            Properties prop = new Properties();
            prop.load(fis);

            host = prop.getProperty("rmi.host");
            port = Integer.parseInt(prop.getProperty("rmi.port"));

            fis.close();

            String url = "rmi://"+host+":"+port+"/fs";

            IRemoteFS service = new RemoteFSImpl();

            //注册端口，外网情况下需要同时注册两个端口
            System.setProperty("java.rmi.server.hostname", host);
            Registry registry = LocateRegistry.createRegistry(port);
            RMISocketFactory.setSocketFactory(new RMISocketFactory() {
                @Override
                public Socket createSocket(String host0, int port0) throws IOException {
                    return new Socket(host, port);
                }

                @Override
                public ServerSocket createServerSocket(int port0) throws IOException {
                    return new ServerSocket(port);
                }
            });
            registry.bind("fs", service);

            logger.info("FS:RMI服务已启动："+url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop(){
        try {
            LocateRegistry.getRegistry(host,port).unbind("fs");
            logger.info("FS:RMI服务已停止");
            System.exit(0);
        } catch (RemoteException | NotBoundException e) {
            e.printStackTrace();
        }
    }
}
